import type {
	IDomEditor,
	IEditorConfig,
	IToolbarConfig,
} from "@wangeditor-next/editor";
import { Editor, Toolbar } from "@wangeditor-next/editor-for-react";
import "@wangeditor-next/editor/dist/css/style.css";
import { useEffect, useState } from "react";

interface RichTextEditorProps {
	onChange?: (value: string) => void;
}

export default function RichTextEditor({ onChange }: RichTextEditorProps) {
	const [editor, setEditor] = useState<IDomEditor | null>(null);
	const [html, setHtml] = useState<string>("");

	const toolbarConfig: Partial<IToolbarConfig> = {};
	const editorConfig: Partial<IEditorConfig> = {
		placeholder: "请输入内容",
	};

	useEffect(() => {
		return () => {
			if (editor == null) return;
			editor.destroy();
			setEditor(null);
		};
	}, [editor]);

	return (
		<div>
			<Toolbar
				editor={editor}
				defaultConfig={toolbarConfig}
				mode="default"
				className="b-b-1 b-solid b-[#ccc]"
			/>
			<Editor
				defaultConfig={editorConfig}
				value={html}
				onCreated={setEditor}
				onChange={(editor) => setHtml(editor.getHtml())}
				mode="default"
				className="h-[500px] overflow-y-hidden"
			/>
		</div>
	);
}
